//
//  ClassNoticeListViewController.m
//  school
//
//  Created by ci123 on 15/5/28.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "ClassNoticeListViewController.h"
#import "MJRefresh.h"
#import "CommonTableViewCell.h"
#import "RequestServerAPI.h"
#import "SDWebImageManager.h"
#import "ImageUtil.h"
#import "ScreenAdapter.h"
#import "NoticeDetailViewController.h"
#import "UserDao.h"
#import "JsonUtil.h"
#import "PopUIManager.h"
#import "NetWorkManager.h"

@interface ClassNoticeListViewController ()
@property UIButton *leftButton;
@end

@implementation ClassNoticeListViewController


@synthesize myTableView, heightList, list_data_array,foot_unit_data_array;

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=NO;
    self.navigationItem.title=@"班级通知";
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 , 44, 44)];
    button.showsTouchWhenHighlighted = YES;
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
    [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    
}

-(void)backButton:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIStatusBarStyle) preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"CommonTableViewCell" owner:self options:nil];
    CommonTableViewCell *cell = (CommonTableViewCell *)[nibArr objectAtIndex:0];
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    CGFloat title_x = CGRectGetMinX(cell.title.frame);
    
    contentW = [ScreenAdapter getInstanse].screenWidth - title_x-10;
    base_height = CGRectGetMaxY(cell.title.frame) + cell.timestamp.frame.size.height + 20;
    
    myTableView.delegate = self;
    myTableView.dataSource = self;
    
    heightList = [NSMutableArray arrayWithCapacity:10];
    
    [self setUpRefreshPlugin];
}

-(void) setFrame:(NSString *)ptype{
    if ([ptype isEqualToString:@"head"]) {
        [heightList removeAllObjects];
        for (NSDictionary* tempDict in list_data_array) {
            
            NSString *content = [tempDict objectForKey:@"content"];
            
            CGSize textSize =  [self sizeWithString:content font:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(contentW, MAXFLOAT)];
            
            double maxY = base_height + textSize.height;
            
            [heightList addObject:[NSNumber numberWithDouble:maxY]];
        }
    }else if ([ptype isEqualToString:@"foot"]){
        for (NSDictionary* tempDict in foot_unit_data_array) {
            
            NSString *content = [tempDict objectForKey:@"content"];
            
            CGSize textSize =  [self sizeWithString:content font:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(contentW, MAXFLOAT)];
            
            double maxY = base_height + textSize.height;
            
            [heightList addObject:[NSNumber numberWithDouble:maxY]];
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    
    CommonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommonTableViewCellID"];
    if (cell == nil) {
        NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"CommonTableViewCell" owner:self options:nil];
        cell = (CommonTableViewCell *)[nibArr objectAtIndex:0];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    NSDictionary* tempDict = [list_data_array objectAtIndex:row];
    NSString *img_url = [tempDict objectForKey:@"icon"];
    if ([img_url isEqualToString:@"null"]) {
        [cell.user_icon setImage:[UIImage imageNamed:@"default_circle_icon"]];
    }else{
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:img_url] options:SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            NSLog(@"进度: %ld",(long)receivedSize);
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            image = [[ImageUtil getInstance] circleImage:image withParam:0];
            [cell.user_icon setImage:image];
        }];
    }
    
    cell.nick_name.text = [tempDict objectForKey:@"name"];
    cell.title.text = [tempDict objectForKey:@"title"];
    cell.content.lineBreakMode = NSLineBreakByCharWrapping;
    cell.content.font = [UIFont systemFontOfSize:14];
    cell.content.text = [tempDict objectForKey:@"content"];
    cell.timestamp.text = [tempDict objectForKey:@"timestamp"];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *temp_dict = [list_data_array objectAtIndex:indexPath.row];
    
    NoticeDetailViewController *ndvc = [[NoticeDetailViewController alloc]init];
    ndvc.my_dict = temp_dict;
    [self.navigationController pushViewController:ndvc animated:YES];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [[heightList objectAtIndex:indexPath.row] doubleValue];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [list_data_array count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}


//======================MJ Refresh Code====================
- (void)setUpRefreshPlugin
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [myTableView addHeaderWithTarget:self action:@selector(headerRefresh)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [myTableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [myTableView addFooterWithTarget:self action:@selector(footerRefresh)];
    
    //设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    myTableView.headerPullToRefreshText = @"下拉刷新";
    myTableView.headerReleaseToRefreshText = @"松开刷新";
    myTableView.headerRefreshingText = @"正在刷新...";
    
    myTableView.footerPullToRefreshText = @"上拉加载";
    myTableView.footerReleaseToRefreshText = @"松开加载";
    myTableView.footerRefreshingText = @"正在加载...";
}

- (void)headerRefresh {
    
    [self apiGetClassNoticeRequestType:@"new" baseId:@"-1"];
}

- (void) setDataForHeaderRefresh:(NSDictionary*)dict{
    //数据重组
    NSString* url_head = [dict objectForKey:@"avatar_header"];
    NSArray *data = [dict objectForKey:@"data"];
    
    list_data_array = [NSMutableArray arrayWithCapacity:data.count];
    
    for (NSDictionary *temp_dict in data) {
        NSMutableDictionary *data_dict = [NSMutableDictionary dictionaryWithCapacity:6];
        
        NSString *head_String = [[temp_dict objectForKey:@"author"] objectForKey:@"avatar"];
        
        if ([head_String isEqual:[NSNull null]]) {
            head_String = @"null";
        }
        
        NSString *user_icon_url = [url_head stringByAppendingString:head_String];
        
        if ([head_String isEqual:@"null"]) {
            user_icon_url = @"null";
        }
        
        NSString *user_nick_name = [[temp_dict objectForKey:@"author"] objectForKey:@"name"];
        NSString *title = [temp_dict objectForKey:@"title"];
        NSString *content = [temp_dict objectForKey:@"content"];
        NSString *timestamp = [temp_dict objectForKey:@"time"];
        NSString *baseid = [temp_dict objectForKey:@"baseid"];
        
        [data_dict setObject:user_icon_url forKey:@"icon"];
        [data_dict setObject:user_nick_name forKey:@"name"];
        [data_dict setObject:title forKey:@"title"];
        [data_dict setObject:content forKey:@"content"];
        [data_dict setObject:timestamp forKey:@"timestamp"];
        [data_dict setObject:baseid forKey:@"baseid"];
        
        NSArray *pic_array = [temp_dict objectForKey:@"pics"];
        NSMutableArray *my_pic_array = [NSMutableArray arrayWithCapacity:pic_array.count];
        for (NSDictionary* pic_dict in pic_array) {
            NSString *pic_url = [url_head stringByAppendingString:[pic_dict objectForKey:@"srcurl"]];
            [my_pic_array addObject:pic_url];
        }
        [data_dict setObject:my_pic_array forKey:@"pics"];
        
        [list_data_array addObject:data_dict];
    }
    
    [self setFrame:@"head"];
    
    [myTableView reloadData];
}

- (void)footerRefresh {
    NSString *baseId = [NSString stringWithFormat:@"%@", ((NSDictionary *)list_data_array.lastObject)[@"baseid"]];
    [self apiGetClassNoticeRequestType:@"old" baseId:baseId];
}

- (void) setDataForFooterRefresh:(NSDictionary*)dict{
    //数据重组
    NSString* url_head = [dict objectForKey:@"avatar_header"];
    NSArray *data = [dict objectForKey:@"data"];
    
    foot_unit_data_array = [NSMutableArray arrayWithCapacity:5];
    
    for (NSDictionary *temp_dict in data) {
        NSMutableDictionary *data_dict = [NSMutableDictionary dictionaryWithCapacity:6];
        
        NSString *head_String = [[temp_dict objectForKey:@"author"] objectForKey:@"avatar"];
        
        if ([head_String isEqual:[NSNull null]]) {
            head_String = @"null";
        }
        
        NSString *user_icon_url = [url_head stringByAppendingString:head_String];
        
        if ([head_String isEqual:@"null"]) {
            user_icon_url = @"null";
        }
        
        
        NSString *user_nick_name = [[temp_dict objectForKey:@"author"] objectForKey:@"name"];
        NSString *title = [temp_dict objectForKey:@"title"];
        NSString *content = [temp_dict objectForKey:@"content"];
        NSString *timestamp = [temp_dict objectForKey:@"time"];
        NSString *baseid = [temp_dict objectForKey:@"baseid"];
        
        [data_dict setObject:user_icon_url forKey:@"icon"];
        [data_dict setObject:user_nick_name forKey:@"name"];
        [data_dict setObject:title forKey:@"title"];
        [data_dict setObject:content forKey:@"content"];
        [data_dict setObject:timestamp forKey:@"timestamp"];
        [data_dict setObject:baseid forKey:@"baseid"];
        
        
        NSArray *pic_array = [temp_dict objectForKey:@"pics"];
        NSMutableArray *my_pic_array = [NSMutableArray arrayWithCapacity:pic_array.count];
        for (NSDictionary* pic_dict in pic_array) {
            NSString *pic_url = [url_head stringByAppendingString:[pic_dict objectForKey:@"srcurl"]];
            [my_pic_array addObject:pic_url];
        }
        [data_dict setObject:my_pic_array forKey:@"pics"];
        
        [list_data_array addObject:data_dict];
        [foot_unit_data_array addObject:data_dict];
    }
    
    [self setFrame:@"foot"];
    
    [myTableView reloadData];
    
}

-(void) stopHeaderRefresh{
    [myTableView headerEndRefreshing];
}

-(void) stopFooterRefresh{
    [myTableView footerEndRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  计算文本的宽高
 *
 *  @param str     需要计算的文本
 *  @param font    文本显示的字体
 *  @param maxSize 文本显示的范围
 *
 *  @return 文本占用的真实宽高
 */
- (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *dict = @{NSFontAttributeName : font};
    // 如果将来计算的文字的范围超出了指定的范围,返回的就是指定的范围
    // 如果将来计算的文字的范围小于指定的范围, 返回的就是真实的范围
    
    CGSize s =  [@"one line" boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    
    
    
    CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    if (s.height * 3 < size.height) {
        return CGSizeMake(size.width, s.height * 3) ;
    }
    
    return size;
}


- (BOOL)apiGetClassNoticeRequestType:(NSString *)requestType baseId:(NSString *)baseId {
    
    NSUInteger classId = [[UserDao getInstance]getCurrentBaby].classid;
    if(classId>0){
        
    }else{
        [self stopHeaderRefresh];
        [self stopFooterRefresh];
        return NO;
    }
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    
    NSDictionary *temp_dict = @{@"uid":uid,
                                @"utype":utype,
                                @"token":[[UserDao getInstance]getAccessToken],
                                @"classid":@(classId),
                                @"dir":requestType,
                                @"baseid":baseId};
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    NSString *msg = @"GET_BANJI_NOTICE";
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if ([requestType isEqualToString:@"new"]) {
            [self stopHeaderRefresh];
        }else if ([requestType isEqualToString:@"old"]){
            [self stopFooterRefresh];
        }
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue] == 1) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        [self setDataForHeaderRefresh:dict];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [self setDataForFooterRefresh:dict];
                    }
                }else if ([[dict objectForKey:@"retCode"] integerValue] == 2){
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"还没有数据哦~" cancelButtonTitle:@"确定"];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"没有更多了哦~" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
    return YES;
}

@end
